package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.mapper.ZjOrganizeMapper;
import com.zb.result.PageUtil;
import com.zb.service.ZjCustomerService;
import com.zb.service.ZjOrganizeEmpService;
import com.zb.service.ZjOrganizeService;
import com.zb.utils.RandomUtil;
import com.zb.vo.OrganizeVo;
import com.zb.vo.OrganizesVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 商家组织表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-07-18
 */
@Service
public class ZjOrganizeServiceImpl extends ServiceImpl<ZjOrganizeMapper, ZjOrganize> implements ZjOrganizeService {
    @Resource
    private ZjOrganizeMapper organizeMapper;
    @Resource
    private ZjOrganizeEmpService organizeEmpService;
    @Resource
    private ZjCustomerService customerService;

    // 新增或修改组织
    @Override
    @Transactional
    public void save(AccounLoginInfo accounLoginInfo, OrganizeVo organizeVo) {
        Assert.isTrue(
                null == organizeMapper.existByName(accounLoginInfo.getCustAccId(), organizeVo.getId(), organizeVo.getParentId(), organizeVo.getName()),
                "该组织已经存在，不可重复添加或修改",
                organizeVo.getName());
        ZjOrganize organize = new ZjOrganize();
        BeanUtils.copyProperties(organizeVo, organize);
        if (null != organize.getId()) {
            this.updateById(organize);
            organizeEmpService.saveOrganizeManagerEmp(accounLoginInfo.getCustAccId(), organize.getId(), organizeVo.getManegerEmpId());
            return;
        }
        organize.setId(IdWorker.getId());
        organize.setCustAccId(accounLoginInfo.getCustAccId());
        organize.setCode(RandomUtil.random28());
        organize.setDisabled(false);
        this.save(organize);
        organizeEmpService.saveOrganizeManagerEmp(accounLoginInfo.getCustAccId(), organize.getId(), organizeVo.getManegerEmpId());
    }

    // 获取组织列表
    @Override
    public List<OrganizesVo> getList(Long custAccId) {
        ZjCustomer customer = customerService.getById(custAccId);

        List<OrganizesVo> organizesVos = new ArrayList<>();
        organizesVos.add(new OrganizesVo(custAccId, 0L, customer.getAbbrevia(), true));

        List<ZjOrganize> organizeList = organizeMapper.getByCustAccId(custAccId);
        organizeList.forEach(t -> organizesVos.add(new OrganizesVo(t.getId(), t.getParentId(), t.getName(), false)));
        return organizesVos.stream().filter(t -> 0 == t.getParentId())
                .map(vo -> {
                    vo.organizesVos(getOragnizeList(vo, organizesVos));
                    return vo;
                }).toList();
    }

    /**
     * 递归获取下级组织
     * @param organizesVo
     * @param organizesVoList
     * @return
     */
    private List<OrganizesVo> getOragnizeList(OrganizesVo organizesVo, List<OrganizesVo> organizesVoList) {
        return organizesVoList.stream().filter(t -> Objects.equals(organizesVo.getId(), t.getParentId()))
                .map(vo -> {
                    vo.organizesVos(getOragnizeList(vo, organizesVoList));
                    return vo;
                }).toList();
    }

    // 根据组织ID获取组织信息
    @Override
    public OrganizeVo getInfo(Long id) {
        ZjOrganize organize = this.getById(id);
        Assert.isTrue(null != organize, "参数[" + id + "]的数据不存在！");
        OrganizeVo vo = new OrganizeVo();
        BeanUtils.copyProperties(organize, vo);
        vo.setManegerEmpId(organizeEmpService.getOrganizeManagerEmpIdByOrganizeId(id));
        return vo;
    }

    // 批量禁用或启用组织
    @Override
    public void updateBatchDisabledById(List<Long> idList, boolean flag) {
        Assert.isTrue(!idList.isEmpty(), "组织ID不能为空", null);
        organizeMapper.updateBatchDisabledById(idList, flag);
    }

    // 批量删除组织
    @Override
    public void deleteBatchById(List<Long> idList) {
        Assert.isTrue(!idList.isEmpty(), "组织ID不能为空", null);
        this.removeByIds(idList);
    }

    // 企业组织下拉数据列表
    @Override
    public Map<String, Object> pageSelecct(Long custAccId, SelectVo selectVo) {
        QueryWrapper<ZjOrganize> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name");
        wrapper.eq("cust_acc_id", custAccId);
        wrapper.eq("is_disabled", false);
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        PageUtil.setSelectPageLimit(selectVo);
        Page<ZjOrganize> page = this.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);
        List<SelectOrganizeVo> voList = new ArrayList<>();
        if (StringUtils.isBlank(selectVo.getName())) {
            ZjCustomer customer = customerService.getById(custAccId);
            voList.add(new SelectOrganizeVo(customer.getId(), customer.getAbbrevia(), true));
        }
        page.getRecords().forEach(t -> voList.add(new SelectOrganizeVo(t.getId(), t.getName(), false)));
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }
}
